<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="温馨提示：本文基于 Kafka 2.2.1 版本。本文主要是以源码的手段一步一步探究消息发送流程，如果对源码不感兴趣，可以直接跳到文末查看消息发送流程图与消息发送本地缓存存储结构。  从上文 初识 Kafka Producer 生产者，可以通过 KafkaProducer 的 send 方法发送消息，send 方法的声明如下： 12Future&lt;RecordMetadata&gt; sen">
<meta property="og:type" content="article">
<meta property="og:title" content="源码分析 Kafka 消息发送流程(文末附流程图)">
<meta property="og:url" content="https://www.codingw.net/posts/f81e58bb.html">
<meta property="og:site_name" content="中间件兴趣圈">
<meta property="og:description" content="温馨提示：本文基于 Kafka 2.2.1 版本。本文主要是以源码的手段一步一步探究消息发送流程，如果对源码不感兴趣，可以直接跳到文末查看消息发送流程图与消息发送本地缓存存储结构。  从上文 初识 Kafka Producer 生产者，可以通过 KafkaProducer 的 send 方法发送消息，send 方法的声明如下： 12Future&lt;RecordMetadata&gt; sen">
<meta property="og:locale">
<meta property="og:image" content="https://img-blog.csdnimg.cn/201911100956254.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20191110101227257.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/201911101014500.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20191110101523210.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">
<meta property="article:published_time" content="2020-10-22T14:56:01.000Z">
<meta property="article:modified_time" content="2021-04-26T12:08:00.032Z">
<meta property="article:author" content="中间件兴趣圈">
<meta property="article:tag" content="中间件">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/201911100956254.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://www.codingw.net/posts/f81e58bb.html"/>





  <title>源码分析 Kafka 消息发送流程(文末附流程图) | 中间件兴趣圈</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">中间件兴趣圈</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">微信搜『中间件兴趣圈』，回复『Java』获取200本优质电子书</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.codingw.net/posts/f81e58bb.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="中间件兴趣圈">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">源码分析 Kafka 消息发送流程(文末附流程图)</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-10-22T22:56:01+08:00">
                2020-10-22
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/kafka/" itemprop="url" rel="index">
                    <span itemprop="name">kafka</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/posts/f81e58bb.html" class="leancloud_visitors" data-flag-title="源码分析 Kafka 消息发送流程(文末附流程图)">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <div id="vip-container"><blockquote>
<p>温馨提示：本文基于 Kafka 2.2.1 版本。本文主要是以源码的手段一步一步探究消息发送流程，如果对源码不感兴趣，可以直接跳到文末查看消息发送流程图与消息发送本地缓存存储结构。</p>
</blockquote>
<p>从上文 <a target="_blank" rel="noopener" href="https://blog.csdn.net/prestigeding/article/details/102881472">初识 Kafka Producer 生产者</a>，可以通过 KafkaProducer 的 send 方法发送消息，send 方法的声明如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">Future&lt;RecordMetadata&gt; <span class="title">send</span><span class="params">(ProducerRecord&lt;K, V&gt; record)</span></span></span><br><span class="line"><span class="function">Future&lt;RecordMetadata&gt; <span class="title">send</span><span class="params">(ProducerRecord&lt;K, V&gt; record, Callback callback)</span></span></span><br></pre></td></tr></table></figure>
<p>从上面的 API 可以得知，用户在使用 KafkaProducer 发送消息时，首先需要将待发送的消息封装成 ProducerRecord，返回的是一个 Future 对象，典型的 Future 设计模式。在发送时也可以指定一个 Callable 接口用来执行消息发送的回调。</p>
<p>我们在学习消息发送流程之前先来看一下用于封装一条消息的 ProducerRecord 的类图，先来认识一下 kafka 是如何对一条消息进行抽象的。</p>
<h2 id="1、ProducerRecord-类图"><a href="#1、ProducerRecord-类图" class="headerlink" title="1、ProducerRecord 类图"></a>1、ProducerRecord 类图</h2><p><img src="https://img-blog.csdnimg.cn/201911100956254.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"><br>我们首先来看一下 ProducerRecord 的核心属性，即构成 消息的6大核心要素：</p>
<ul>
<li>String topic<br>消息所属的主题。</li>
<li>Integer partition<br>消息所在主题的队列数，可以人为指定，如果指定了 key 的话，会使用 key 的 hashCode 与队列总数进行取模来选择分区，如果前面两者都未指定，则会轮询主题下的所有分区。</li>
<li>Headers headers<br>该消息的额外属性对，与消息体分开存储.</li>
<li>K key<br>消息键，如果指定该值，则会使用该值的 hashcode 与 队列数进行取模来选择分区。</li>
<li>V value<br>消息体。</li>
<li>Long timestamp<br>消息时间戳，根据 topic 的配置信息 message.timestamp.type 的值来赋予不同的值。<ul>
<li>CreateTime<br>发送客户端发送消息时的时间戳。</li>
<li>LogAppendTime<br>消息在 broker 追加时的时间戳。</li>
</ul>
</li>
</ul>
<p>其中Headers是一系列的 key-value 键值对。</p>
<p>在了解 ProducerRecord 后我们开始来探讨 Kafka 的消息发送流程。</p>
<span id="more"></span>

<h2 id="2、Kafka-消息追加流程"><a href="#2、Kafka-消息追加流程" class="headerlink" title="2、Kafka 消息追加流程"></a>2、Kafka 消息追加流程</h2><p>KafkaProducer 的 send 方法，并不会直接向 broker 发送消息，kafka 将消息发送异步化，即分解成两个步骤，send 方法的职责是将消息追加到内存中(分区的缓存队列中)，然后会由专门的 Send 线程异步将缓存中的消息批量发送到 Kafka Broker 中。</p>
<p>消息追加入口为 KafkaProducer#send</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Future&lt;RecordMetadata&gt; <span class="title">send</span><span class="params">(ProducerRecord&lt;K, V&gt; record, Callback callback)</span> </span>&#123;  </span><br><span class="line">    <span class="comment">// intercept the record, which can be potentially modified; this method does not throw exceptions</span></span><br><span class="line">    ProducerRecord&lt;K, V&gt; interceptedRecord = <span class="keyword">this</span>.interceptors.onSend(record);                <span class="comment">// @1</span></span><br><span class="line">    <span class="keyword">return</span> doSend(interceptedRecord, callback);                                                                     <span class="comment">// @2</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：首先执行消息发送拦截器，拦截器通过 interceptor.classes 指定，类型为 List&lt; String &gt;，每一个元素为拦截器的全类路径限定名。<br>代码@2：执行 doSend 方法，后续我们需要留意一下 Callback  的调用时机。</p>
<p>接下来我们来看 doSend 方法。</p>
<h3 id="2-1-doSend"><a href="#2-1-doSend" class="headerlink" title="2.1 doSend"></a>2.1 doSend</h3><p>KafkaProducer#doSend</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">ClusterAndWaitTime clusterAndWaitTime;</span><br><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">    clusterAndWaitTime = waitOnMetadata(record.topic(), record.partition(), maxBlockTimeMs);</span><br><span class="line">&#125; <span class="keyword">catch</span> (KafkaException e) &#123;</span><br><span class="line">    <span class="keyword">if</span> (metadata.isClosed())</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> KafkaException(<span class="string">&quot;Producer closed while send in progress&quot;</span>, e);</span><br><span class="line">	<span class="keyword">throw</span> e;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">long</span> remainingWaitMs = Math.max(<span class="number">0</span>, maxBlockTimeMs - clusterAndWaitTime.waitedOnMetadataMs);</span><br></pre></td></tr></table></figure>
<p>Step1：获取 topic 的分区列表，如果本地没有该topic的分区信息，则需要向远端 broker 获取，该方法会返回拉取元数据所耗费的时间。在消息发送时的最大等待时间时会扣除该部分损耗的时间。</p>
<blockquote>
<p>温馨提示：本文不打算对该方法进行深入学习，后续会有专门的文章来分析 Kafka 元数据的同步机制，类似于专门介绍 RocketMQ 的 Nameserver 类似。</p>
</blockquote>
<p>KafkaProducer#doSend</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">byte</span>[] serializedKey;</span><br><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">    serializedKey = keySerializer.serialize(record.topic(), record.headers(), record.key());</span><br><span class="line">&#125; <span class="keyword">catch</span> (ClassCastException cce) &#123;</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span> SerializationException(<span class="string">&quot;Can&#x27;t convert key of class &quot;</span> + record.key().getClass().getName() +</span><br><span class="line">                        <span class="string">&quot; to class &quot;</span> + producerConfig.getClass(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG).getName() +</span><br><span class="line">                        <span class="string">&quot; specified in key.serializer&quot;</span>, cce);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Step2：序列化 key。注意：序列化方法虽然有传入 topic、Headers 这两个属性，但参与序列化的只是 key 。</p>
<p>KafkaProducer#doSend</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">byte</span>[] serializedValue;</span><br><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">    serializedValue = valueSerializer.serialize(record.topic(), record.headers(), record.value());</span><br><span class="line">&#125; <span class="keyword">catch</span> (ClassCastException cce) &#123;</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span> SerializationException(<span class="string">&quot;Can&#x27;t convert value of class &quot;</span> + record.value().getClass().getName() +</span><br><span class="line">                        <span class="string">&quot; to class &quot;</span> + producerConfig.getClass(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG).getName() +</span><br><span class="line">                        <span class="string">&quot; specified in value.serializer&quot;</span>, cce);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Step3：对消息体内容进行序列化。</p>
<p>KafkaProducer#doSend</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span> partition = partition(record, serializedKey, serializedValue, cluster);</span><br><span class="line">tp = <span class="keyword">new</span> TopicPartition(record.topic(), partition);</span><br></pre></td></tr></table></figure>
<p>Step4：根据分区负载算法计算本次消息发送该发往的分区。其默认实现类为 DefaultPartitioner，路由算法如下：</p>
<ul>
<li>如果指定了 key ，则使用 key 的 hashcode 与分区数取模。</li>
<li>如果未指定 key，则轮询所有的分区。</li>
</ul>
<p>KafkaProducer#doSend</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">setReadOnly(record.headers());</span><br><span class="line">Header[] headers = record.headers().toArray();</span><br></pre></td></tr></table></figure>
<p>Step5：如果是消息头信息(RecordHeaders)，则设置为只读。</p>
<p>KafkaProducer#doSend</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span> serializedSize = AbstractRecords.estimateSizeInBytesUpperBound(apiVersions.maxUsableProduceMagic(),</span><br><span class="line">                    compressionType, serializedKey, serializedValue, headers);</span><br><span class="line">ensureValidRecordSize(serializedSize);</span><br></pre></td></tr></table></figure>
<p>Step5：根据使用的版本号，按照消息协议来计算消息的长度，并是否超过指定长度，如果超过则抛出异常。</p>
<p>KafkaProducer#doSend</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">long</span> timestamp = record.timestamp() == <span class="keyword">null</span> ? time.milliseconds() : record.timestamp();</span><br><span class="line">log.trace(<span class="string">&quot;Sending record &#123;&#125; with callback &#123;&#125; to topic &#123;&#125; partition &#123;&#125;&quot;</span>, record, callback, record.topic(), partition);</span><br><span class="line">Callback interceptCallback = <span class="keyword">new</span> InterceptorCallback&lt;&gt;(callback, <span class="keyword">this</span>.interceptors, tp);</span><br></pre></td></tr></table></figure>
<p>Step6：先初始化消息时间戳，并对传入的 Callable(回调函数) 加入到拦截器链中。</p>
<p>KafkaProducer#doSend</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (transactionManager != <span class="keyword">null</span> &amp;&amp; transactionManager.isTransactional())</span><br><span class="line">    transactionManager.maybeAddPartitionToTransaction(tp);</span><br></pre></td></tr></table></figure>
<p>Step7：如果事务处理器不为空，执行事务管理相关的，本节不考虑事务消息相关的实现细节，后续估计会有对应的文章进行解析。</p>
<p>KafkaProducer#doSend</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">RecordAccumulator.RecordAppendResult result = accumulator.append(tp, timestamp, serializedKey, serializedValue, headers, interceptCallback, remainingWaitMs);</span><br><span class="line"><span class="keyword">if</span> (result.batchIsFull || result.newBatchCreated) &#123;</span><br><span class="line">    log.trace(<span class="string">&quot;Waking up the sender since topic &#123;&#125; partition &#123;&#125; is either full or getting a new batch&quot;</span>, record.topic(), partition);</span><br><span class="line">                <span class="keyword">this</span>.sender.wakeup();</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">return</span> result.future;</span><br></pre></td></tr></table></figure>
<p>Step8：将消息追加到缓存区，这将是本文重点需要探讨的。如果当前缓存区已写满或创建了一个新的缓存区，则唤醒 Sender(消息发送线程)，将缓存区中的消息发送到 broker 服务器，最终返回 future。这里是经典的 Future 设计模式，从这里也能得知，doSend 方法执行完成后，此时消息还不一定成功发送到 broker。</p>
<p>KafkaProducer#doSend</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">&#125; catch (ApiException e) &#123;</span><br><span class="line">    log.debug(&quot;Exception occurred during message send:&quot;, e);</span><br><span class="line">    if (callback !&#x3D; null)</span><br><span class="line">        callback.onCompletion(null, e);</span><br><span class="line">        </span><br><span class="line">	this.errors.record();</span><br><span class="line">    this.interceptors.onSendError(record, tp, e);</span><br><span class="line">        return new FutureFailure(e);</span><br><span class="line">&#125; catch (InterruptedException e) &#123;</span><br><span class="line">    this.errors.record();</span><br><span class="line">    this.interceptors.onSendError(record, tp, e);</span><br><span class="line">    throw new InterruptException(e);</span><br><span class="line">&#125; catch (BufferExhaustedException e) &#123;</span><br><span class="line">    this.errors.record();</span><br><span class="line">    this.metrics.sensor(&quot;buffer-exhausted-records&quot;).record();</span><br><span class="line">    this.interceptors.onSendError(record, tp, e);</span><br><span class="line">    throw e;</span><br><span class="line">&#125; catch (KafkaException e) &#123;</span><br><span class="line">    this.errors.record();</span><br><span class="line">    this.interceptors.onSendError(record, tp, e);</span><br><span class="line">    throw e;</span><br><span class="line">&#125; catch (Exception e) &#123;</span><br><span class="line">    &#x2F;&#x2F; we notify interceptor about all exceptions, since onSend is called before anything else in this method</span><br><span class="line">    this.interceptors.onSendError(record, tp, e);</span><br><span class="line">    throw e;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Step9：针对各种异常，进行相关信息的收集。</p>
<p>接下来将重点介绍如何将消息追加到生产者的发送缓存区，其实现类为：RecordAccumulator。</p>
<h3 id="2-2-RecordAccumulator-append-方法详解"><a href="#2-2-RecordAccumulator-append-方法详解" class="headerlink" title="2.2 RecordAccumulator append 方法详解"></a>2.2 RecordAccumulator append 方法详解</h3><p>RecordAccumulator#append</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> RecordAppendResult <span class="title">append</span><span class="params">(TopicPartition tp,</span></span></span><br><span class="line"><span class="function"><span class="params">                                     <span class="keyword">long</span> timestamp,</span></span></span><br><span class="line"><span class="function"><span class="params">                                     <span class="keyword">byte</span>[] key,</span></span></span><br><span class="line"><span class="function"><span class="params">                                     <span class="keyword">byte</span>[] value,</span></span></span><br><span class="line"><span class="function"><span class="params">                                     Header[] headers,</span></span></span><br><span class="line"><span class="function"><span class="params">                                     Callback callback,</span></span></span><br><span class="line"><span class="function"><span class="params">                                     <span class="keyword">long</span> maxTimeToBlock)</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br></pre></td></tr></table></figure>
<p>在介绍该方法之前，我们首先来看一下该方法的参数。</p>
<ul>
<li>TopicPartition tp<br>topic 与分区信息，即发送到哪个 topic 的那个分区。</li>
<li>long timestamp<br>客户端发送时的时间戳。</li>
<li>byte[] key<br>消息的 key。</li>
<li>byte[] value<br>消息体。</li>
<li>Header[] headers<br>消息头，可以理解为额外消息属性。</li>
<li>Callback callback<br>回调方法。</li>
<li>long maxTimeToBlock<br>消息追加超时时间。</li>
</ul>
<p>RecordAccumulator#append</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">Deque&lt;ProducerBatch&gt; dq = getOrCreateDeque(tp);</span><br><span class="line"><span class="keyword">synchronized</span> (dq) &#123;</span><br><span class="line">    <span class="keyword">if</span> (closed)</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> KafkaException(<span class="string">&quot;Producer closed while send in progress&quot;</span>);</span><br><span class="line">    RecordAppendResult appendResult = tryAppend(timestamp, key, value, headers, callback, dq);</span><br><span class="line">    <span class="keyword">if</span> (appendResult != <span class="keyword">null</span>)</span><br><span class="line">        <span class="keyword">return</span> appendResult;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Step1：尝试根据 topic与分区在 kafka 中获取一个双端队列，如果不存在，则创建一个，然后调用 tryAppend 方法将消息追加到缓存中。Kafka 会为每一个 topic 的每一个分区创建一个消息缓存区，消息先追加到缓存中，然后消息发送 API 立即返回，然后由单独的线程 Sender 将缓存区中的消息定时发送到 broker 。这里的缓存区的实现使用的是 ArrayQeque。然后调用 tryAppend 方法尝试将消息追加到其缓存区，如果追加成功，则返回结果。</p>
<p>在讲解下一个流程之前，我们先来看一下 Kafka 双端队列的存储结构：<br><img src="https://img-blog.csdnimg.cn/20191110101227257.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"></p>
<p>RecordAccumulator#append</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span> size = Math.max(<span class="keyword">this</span>.batchSize, AbstractRecords.estimateSizeInBytesUpperBound(maxUsableMagic, compression, key, value, headers));</span><br><span class="line">log.trace(<span class="string">&quot;Allocating a new &#123;&#125; byte message buffer for topic &#123;&#125; partition &#123;&#125;&quot;</span>, size, tp.topic(), tp.partition());</span><br><span class="line">buffer = free.allocate(size, maxTimeToBlock);</span><br></pre></td></tr></table></figure>
<p>Step2：如果第一步未追加成功，说明当前没有可用的 ProducerBatch，则需要创建一个 ProducerBatch，故先从 BufferPool 中申请 batch.size 的内存空间，为创建 ProducerBatch 做准备，如果由于 BufferPool 中未有剩余内存，则最多等待 maxTimeToBlock ，如果在指定时间内未申请到内存，则抛出异常。</p>
<p>RecordAccumulator#append</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">synchronized</span> (dq) &#123;</span><br><span class="line">    <span class="comment">// Need to check if producer is closed again after grabbing the dequeue lock.</span></span><br><span class="line">    <span class="keyword">if</span> (closed)</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> KafkaException(<span class="string">&quot;Producer closed while send in progress&quot;</span>);</span><br><span class="line">    <span class="comment">// 省略部分代码</span></span><br><span class="line">    MemoryRecordsBuilder recordsBuilder = recordsBuilder(buffer, maxUsableMagic);</span><br><span class="line">    ProducerBatch batch = <span class="keyword">new</span> ProducerBatch(tp, recordsBuilder, time.milliseconds());</span><br><span class="line">    FutureRecordMetadata future = Utils.notNull(batch.tryAppend(timestamp, key, value, headers, callback, time.milliseconds()));</span><br><span class="line">    dq.addLast(batch);</span><br><span class="line">    incomplete.add(batch);</span><br><span class="line">    <span class="comment">// Don&#x27;t deallocate this buffer in the finally block as it&#x27;s being used in the record batch</span></span><br><span class="line">    buffer = <span class="keyword">null</span>;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> RecordAppendResult(future, dq.size() &gt; <span class="number">1</span> || batch.isFull(), <span class="keyword">true</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Step3：创建一个新的批次 ProducerBatch，并将消息写入到该批次中，并返回追加结果，这里有如下几个关键点：</p>
<ul>
<li>创建 ProducerBatch ，其内部持有一个 MemoryRecordsBuilder对象，该对象负责将消息写入到内存中，即写入到 ProducerBatch 内部持有的内存，大小等于 batch.size。</li>
<li>将消息追加到 ProducerBatch 中。</li>
<li>将新创建的 ProducerBatch  添加到双端队列的末尾。</li>
<li>将该批次加入到 incomplete 容器中，该容器存放未完成发送到 broker 服务器中的消息批次，当 Sender 线程将消息发送到 broker 服务端后，会将其移除并释放所占内存。</li>
<li>返回追加结果。</li>
</ul>
<p>纵观 RecordAccumulator  append 的流程，基本上就是从双端队列获取一个未填充完毕的 ProducerBatch（消息批次），然后尝试将其写入到该批次中（缓存、内存中），如果追加失败，则尝试创建一个新的 ProducerBatch 然后继续追加。</p>
<p>接下来我们继续探究如何向 ProducerBatch 中写入消息。</p>
<h3 id="2-3-ProducerBatch-tryAppend方法详解"><a href="#2-3-ProducerBatch-tryAppend方法详解" class="headerlink" title="2.3 ProducerBatch  tryAppend方法详解"></a>2.3 ProducerBatch  tryAppend方法详解</h3><p>ProducerBatch #tryAppend</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> FutureRecordMetadata <span class="title">tryAppend</span><span class="params">(<span class="keyword">long</span> timestamp, <span class="keyword">byte</span>[] key, <span class="keyword">byte</span>[] value, Header[] headers, Callback callback, <span class="keyword">long</span> now)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (!recordsBuilder.hasRoomFor(timestamp, key, value, headers)) &#123;  <span class="comment">// @1</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        Long checksum = <span class="keyword">this</span>.recordsBuilder.append(timestamp, key, value, headers);                    <span class="comment">// @2</span></span><br><span class="line">        <span class="keyword">this</span>.maxRecordSize = Math.max(<span class="keyword">this</span>.maxRecordSize, AbstractRecords.estimateSizeInBytesUpperBound(magic(),</span><br><span class="line">                    recordsBuilder.compressionType(), key, value, headers));               <span class="comment">// @3</span></span><br><span class="line">        <span class="keyword">this</span>.lastAppendTime = now;                                                                          <span class="comment">//                                                     </span></span><br><span class="line">        FutureRecordMetadata future = <span class="keyword">new</span> FutureRecordMetadata(<span class="keyword">this</span>.produceFuture, <span class="keyword">this</span>.recordCount,</span><br><span class="line">                                                                   timestamp, checksum,</span><br><span class="line">                                                                   key == <span class="keyword">null</span> ? -<span class="number">1</span> : key.length,</span><br><span class="line">                                                                   value == <span class="keyword">null</span> ? -<span class="number">1</span> : value.length,</span><br><span class="line">                                                                   Time.SYSTEM);                                        <span class="comment">// @4</span></span><br><span class="line">        <span class="comment">// we have to keep every future returned to the users in case the batch needs to be</span></span><br><span class="line">        <span class="comment">// split to several new batches and resent.</span></span><br><span class="line">        thunks.add(<span class="keyword">new</span> Thunk(callback, future));                                                           <span class="comment">// @5</span></span><br><span class="line">        <span class="keyword">this</span>.recordCount++;</span><br><span class="line">        <span class="keyword">return</span> future;                                                                            </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：首先判断 ProducerBatch  是否还能容纳当前消息，如果剩余内存不足，将直接返回 null。如果返回 null ，会尝试再创建一个新的ProducerBatch。</p>
<p>代码@2：通过 MemoryRecordsBuilder 将消息写入按照 Kafka 消息格式写入到内存中，即写入到 在创建 ProducerBatch  时申请的 ByteBuffer 中。本文先不详细介绍 Kafka 各个版本的消息格式，后续会专门写一篇文章介绍 Kafka 各个版本的消息格式。</p>
<p>代码@3：更新 ProducerBatch  的 maxRecordSize、lastAppendTime 属性，分别表示该批次中最大的消息长度与最后一次追加消息的时间。</p>
<p>代码@4：构建 FutureRecordMetadata 对象，这里是典型的 Future模式，里面主要包含了该条消息对应的批次的 produceFuture、消息在该批消息的下标，key 的长度、消息体的长度以及当前的系统时间。</p>
<p>代码@5：将 callback 、本条消息的凭证(Future) 加入到该批次的 thunks 中，该集合存储了 一个批次中所有消息的发送回执。</p>
<p>流程执行到这里，KafkaProducer 的 send 方法就执行完毕了，返回给调用方的就是一个 FutureRecordMetadata 对象。</p>
<p>源码的阅读比较枯燥，接下来用一个流程图简单的阐述一下消息追加的关键要素，重点关注一下各个 Future。</p>
<h3 id="2-4-Kafka-消息追加流程图与总结"><a href="#2-4-Kafka-消息追加流程图与总结" class="headerlink" title="2.4 Kafka 消息追加流程图与总结"></a>2.4 Kafka 消息追加流程图与总结</h3><p><img src="https://img-blog.csdnimg.cn/201911101014500.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"><br>上面的消息发送，其实用消息追加来表达更加贴切，因为 Kafka 的 send 方法，并不会直接向 broker 发送消息，而是首先先追加到生产者的内存缓存中，其内存存储结构如下：ConcurrentMap&lt; TopicPartition, Deque&lt; ProducerBatch&gt;&gt; batches，那我们自然而然的可以得知，Kafka 的生产者为会每一个 topic 的每一个 分区单独维护一个队列，即 ArrayDeque，内部存放的元素为 ProducerBatch，即代表一个批次，即 Kafka 消息发送是按批发送的。其缓存结果图如下：<br><img src="https://img-blog.csdnimg.cn/20191110101523210.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"><br>KafkaProducer 的 send 方法最终返回的 FutureRecordMetadata ，是 Future 的子类，即 Future 模式。那 kafka 的消息发送怎么实现异步发送、同步发送的呢？</p>
<p>其实答案也就蕴含在 send 方法的返回值，如果项目方需要使用同步发送的方式，只需要拿到 send 方法的返回结果后，调用其 get() 方法，此时如果消息还未发送到 Broker 上，该方法会被阻塞，等到 broker 返回消息发送结果后该方法会被唤醒并得到消息发送结果。如果需要异步发送，则建议使用 send(ProducerRecord&lt; K, V &gt; record, Callback callback),但不能调用 get 方法即可。Callback 会在收到 broker 的响应结果后被调用，并且支持拦截器。</p>
<p>消息追加流程就介绍到这里了，消息被追加到缓存区后，什么是会被发送到 broker 端呢？将在下一篇文章中详细介绍。</p>
<p>如果文章对您有所帮助的话，麻烦帮忙点个赞，谢谢您的认可与支持。</p>
</div>

			<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
			<script>
			var isMobile = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
			if (!isMobile) {
			    var btw = new BTWPlugin();
			    btw.init({
			        "id": "vip-container",
			        "blogId": "18019-1573088808868-542",
			        "name": "中间件兴趣圈",
			        "qrcode": "https://img-blog.csdnimg.cn/20190314214003962.jpg",
			        "keyword": "more"
			    });
			}
			</script>
		
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/fc4470e5.html" rel="next" title="一次 RocketMQ 进程自动退出排查经验分享（实战篇）">
                <i class="fa fa-chevron-left"></i> 一次 RocketMQ 进程自动退出排查经验分享（实战篇）
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/497923c7.html" rel="prev" title="源码分析Kafka 消息拉取流程">
                源码分析Kafka 消息拉取流程 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">139</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1%E3%80%81ProducerRecord-%E7%B1%BB%E5%9B%BE"><span class="nav-number">1.</span> <span class="nav-text">1、ProducerRecord 类图</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2%E3%80%81Kafka-%E6%B6%88%E6%81%AF%E8%BF%BD%E5%8A%A0%E6%B5%81%E7%A8%8B"><span class="nav-number">2.</span> <span class="nav-text">2、Kafka 消息追加流程</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1-doSend"><span class="nav-number">2.1.</span> <span class="nav-text">2.1 doSend</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-2-RecordAccumulator-append-%E6%96%B9%E6%B3%95%E8%AF%A6%E8%A7%A3"><span class="nav-number">2.2.</span> <span class="nav-text">2.2 RecordAccumulator append 方法详解</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-3-ProducerBatch-tryAppend%E6%96%B9%E6%B3%95%E8%AF%A6%E8%A7%A3"><span class="nav-number">2.3.</span> <span class="nav-text">2.3 ProducerBatch  tryAppend方法详解</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-4-Kafka-%E6%B6%88%E6%81%AF%E8%BF%BD%E5%8A%A0%E6%B5%81%E7%A8%8B%E5%9B%BE%E4%B8%8E%E6%80%BB%E7%BB%93"><span class="nav-number">2.4.</span> <span class="nav-text">2.4 Kafka 消息追加流程图与总结</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">中间件兴趣圈</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("NNEhOL0iOcflg8f1U3HUqiCq-gzGzoHsz", "7kSmkbbb3DktmHALlShDsBUF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
